<template>
  <div class="workflow-category-page">
    <!-- 查询表单 -->
    <CategorySearchForm
      :loading="loading"
      @search="handleSearch"
      @reset="handleReset"
      @update:search-params="handleSearchParamsChange"
    />
    
    <!-- 分类列表 -->
    <CategoryList
      :table-data="tableData"
      :pagination="pagination"
      :loading="loading"
      :selection="selection"
      @update:selection="handleSelectionChange"
      @page-change="handlePageChange"
      @sort="handleSort"
      @refresh="handleRefresh"
      @export="handleExport"
      @add="handleAdd"
      @action="handleAction"
    />
    
    <!-- 新增分类弹窗 -->
    <CategoryAddDialog
      v-model:visible="addDialogVisible"
      :loading="dialogLoading"
      :category-options="categoryOptions"
      @submit="handleAddSubmit"
      @close="handleAddClose"
    />
    
    <!-- 编辑分类弹窗 -->
    <CategoryEditDialog
      v-model:visible="editDialogVisible"
      :category-data="editingCategory"
      :category-options="categoryOptions"
      :loading="dialogLoading"
      @submit="handleEditSubmit"
      @close="handleEditClose"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import CategorySearchForm from './modules/CategorySearchForm.vue'
import CategoryList from './modules/CategoryList.vue'
import CategoryAddDialog from './modules/CategoryAddDialog.vue'
import CategoryEditDialog from './modules/CategoryEditDialog.vue'
import type { Pagination, TableAction } from '@/types'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const dialogLoading = ref(false)
const selection = ref<any[]>([])
const searchParams = ref({})

// 弹窗状态
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const editingCategory = ref<any>(null)

const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const tableData = ref([
  {
    categoryId: 1,
    parentId: 0,
    categoryName: '请假流程',
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-15 14:30:00'
  },
  {
    categoryId: 2,
    parentId: 0,
    categoryName: '报销流程',
    createTime: '2024-01-02 09:15:00',
    updateTime: '2024-01-14 16:20:00'
  },
  {
    categoryId: 3,
    parentId: 1,
    categoryName: '事假',
    createTime: '2024-01-03 11:30:00',
    updateTime: '2024-01-13 10:15:00'
  },
  {
    categoryId: 4,
    parentId: 1,
    categoryName: '病假',
    createTime: '2024-01-04 14:45:00',
    updateTime: '2024-01-12 09:30:00'
  },
  {
    categoryId: 5,
    parentId: 2,
    categoryName: '差旅报销',
    createTime: '2024-01-05 16:20:00',
    updateTime: '2024-01-11 11:45:00'
  }
])

// 分类选项（用于父级分类选择）
const categoryOptions = computed(() => {
  const options = [
    { label: '顶级分类', value: 0 }
  ]
  
  // 将表格数据转换为选项
  const convertToOptions = (data: any[]) => {
    data.forEach(item => {
      options.push({
        label: item.categoryName,
        value: item.categoryId
      })
    })
  }
  
  convertToOptions(tableData.value)
  return options
})

// 初始化数据
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新分页信息
    pagination.total = 15 // 模拟总数
    
    console.log('加载流程分类数据:', {
      searchParams: searchParams.value,
      pagination: pagination
    })
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理搜索参数变化
const handleSearchParamsChange = (params: Record<string, any>) => {
  searchParams.value = params
}

// 处理搜索
const handleSearch = (params: Record<string, any>) => {
  console.log('搜索参数:', params)
  searchParams.value = params
  pagination.currentPage = 1
  loadData()
}

// 处理重置
const handleReset = () => {
  console.log('重置搜索')
  searchParams.value = {}
  pagination.currentPage = 1
  loadData()
}

// 处理选择变化
const handleSelectionChange = (newSelection: any[]) => {
  console.log('选择变化:', newSelection)
  selection.value = newSelection
}

// 处理分页变化
const handlePageChange = (page: number, pageSize: number) => {
  console.log('分页变化:', page, pageSize)
  pagination.currentPage = page
  pagination.pageSize = pageSize
  loadData()
}

// 处理排序
const handleSort = (sortField: string, sortOrder: number) => {
  console.log('排序变化:', sortField, sortOrder)
  loadData()
}

// 处理刷新
const handleRefresh = () => {
  console.log('刷新数据')
  loadData()
}

// 处理导出
const handleExport = () => {
  console.log('导出数据')
  // 实现导出逻辑
}

// 处理新增
const handleAdd = () => {
  console.log('新增流程分类')
  addDialogVisible.value = true
}

// 处理操作
const handleAction = (action: TableAction, row: any, index: number) => {
  console.log('执行操作:', action.key, row, index)
  
  switch (action.key) {
    case 'edit':
      editingCategory.value = row
      editDialogVisible.value = true
      break
    case 'delete':
      if (confirm(`确定要删除分类 "${row.categoryName}" 吗？`)) {
        deleteCategory(row.categoryId)
      }
      break
  }
}

// 处理新增提交
const handleAddSubmit = async (data: any) => {
  dialogLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 添加到表格数据
    const newCategory = {
      categoryId: Date.now(),
      ...data,
      createTime: new Date().toLocaleString('zh-CN'),
      updateTime: new Date().toLocaleString('zh-CN')
    }
    
    tableData.value.unshift(newCategory)
    pagination.total++
    
    addDialogVisible.value = false
    console.log('新增流程分类成功:', newCategory)
  } catch (error) {
    console.error('新增流程分类失败:', error)
  } finally {
    dialogLoading.value = false
  }
}

// 处理新增关闭
const handleAddClose = () => {
  addDialogVisible.value = false
}

// 处理编辑提交
const handleEditSubmit = async (data: any) => {
  dialogLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新表格数据
    const index = tableData.value.findIndex(item => item.categoryId === data.categoryId)
    if (index > -1) {
      tableData.value[index] = {
        ...tableData.value[index],
        ...data,
        updateTime: new Date().toLocaleString('zh-CN')
      }
    }
    
    editDialogVisible.value = false
    editingCategory.value = null
    console.log('编辑流程分类成功:', data)
  } catch (error) {
    console.error('编辑流程分类失败:', error)
  } finally {
    dialogLoading.value = false
  }
}

// 处理编辑关闭
const handleEditClose = () => {
  editDialogVisible.value = false
  editingCategory.value = null
}

// 删除分类
const deleteCategory = async (categoryId: number) => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 从表格数据中移除
    const index = tableData.value.findIndex(item => item.categoryId === categoryId)
    if (index > -1) {
      tableData.value.splice(index, 1)
      pagination.total--
    }
    
    console.log('删除流程分类成功:', categoryId)
  } catch (error) {
    console.error('删除流程分类失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.workflow-category-page {
  padding: 0;
}
</style>